package br.ufrgs.jsopa;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;

public class Main {

    private static boolean systemOn = true;
    private static boolean roundRobinSchedulling = true;
    public static final int SLEEP_TIME = 500; // original was 50ms
    private static BufferedWriter outPrint;// our fileWriter
    private static IntController i;
    private static Memory m;
    private static Console c;
    private static Timer t;
    private static Disco d;
    private static Processor p;

    /**
     * The program models a complete computer with most HW components The
     * kernel, which is the software component, might have been created here
     * also, but Processor has a reference to it and it has a reference to the
     * processor, so I decided that all software is under the processor
     * environment: kernel inside processor.
     *
     * @param args
     */
    public static void main(String args[]) {
        printInit();

        i = new IntController();
        m = new Memory(1024);
        c = new Console(i);
        t = new Timer(i);
        d = new Disco(i, m);
        p = new Processor(i, m, c, t, d);

        // start all threads
        p.start();
        c.start();
        t.start();
        d.start();
    }

    public static void printInit() {
        try {
            outPrint = new BufferedWriter(new FileWriter("log.txt"));
            Date date = new Date();
            print("Logging execution started.");
            print("---------------------------------------------------------------");
            print(null);
        } catch (IOException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public static synchronized void print(String line) {
        if (line == null) {
            line = "";// empty line
        }

        // print to console
        System.err.println(line);

        // print to file
        try {
            outPrint.write(line + "\n");
            outPrint.flush();
        } catch (IOException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public static boolean isSystemOn() {
        return systemOn;
    }

    public static void setSystemOff() {
        print("ATTENTION: system is shutting down!!!");
        Main.systemOn = false;
    }

    public static boolean isRoundRobinSchedulling() {
        return roundRobinSchedulling;
    }

    public static void setRoundRobinSchedulling(boolean roundRobinSchedulling) {
        Main.roundRobinSchedulling = roundRobinSchedulling;
    }
}